﻿using BrightIdeasSoftware;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FormTest
{
    public partial class Form6 : Form
    {
        private DataListView _dataListView;
        private DataTable _fileData;
        private ImageList _fileImageList;
        private IconCache _iconCache; // 图标缓存
                                      // Windows API 用于获取文件图标
        [DllImport("shell32.dll", CharSet = CharSet.Auto)]
        private static extern IntPtr SHGetFileInfo(
            string pszPath,
            uint dwFileAttributes,
            ref SHFILEINFO psfi,
            uint cbSizeFileInfo,
            uint uFlags);

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        private struct SHFILEINFO
        {
            public IntPtr hIcon;
            public int iIcon;
            public uint dwAttributes;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
            public string szDisplayName;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
            public string szTypeName;
        }
        // 图标缓存类（避免重复获取）
        private class IconCache
        {
            private readonly Dictionary<string, int> _extensionCache = new Dictionary<string, int>();
            private readonly ImageList _imageList;

            public IconCache(ImageList imageList)
            {
                _imageList = imageList;
            }

            // 获取文件扩展名对应的图标索引
            public int GetIconIndex(string filePath)
            {
                string extension = Path.GetExtension(filePath).ToLower();
                bool isDirectory = Directory.Exists(filePath);

                // 目录使用特殊键
                string cacheKey = isDirectory ? "directory" : extension;

                // 检查缓存
                if (_extensionCache.TryGetValue(cacheKey, out int index))
                    return index;

                // 缓存未命中，获取新图标
                index = AddIconToImageList(filePath, isDirectory);
                _extensionCache[cacheKey] = index;
                return index;
            }

            // 添加图标到ImageList并返回索引
            private int AddIconToImageList(string path, bool isDirectory)
            {
                var shfi = new SHFILEINFO();
                const uint SHGFI_ICON = 0x100;
                const uint SHGFI_SMALLICON = 0x00000001;
                const uint SHGFI_USEFILEATTRIBUTES = 0x000000010;
                const uint FILE_ATTRIBUTE_DIRECTORY = 0x00000010;

                uint flags = SHGFI_ICON | SHGFI_SMALLICON;
                uint attributes = 0;

                if (isDirectory)
                {
                    attributes = FILE_ATTRIBUTE_DIRECTORY;
                    flags |= SHGFI_USEFILEATTRIBUTES;
                }

                // 调用API获取图标
                SHGetFileInfo(path, attributes, ref shfi, (uint)Marshal.SizeOf(shfi), flags);

                // 将图标添加到ImageList
                using (Icon icon = Icon.FromHandle(shfi.hIcon))
                {
                    _imageList.Images.Add((Icon)icon.Clone()); // 克隆避免句柄问题
                }

                return _imageList.Images.Count - 1;
            }
        }
        public Form6()
        {
            InitializeComponent();
            InitializeImageList();
            InitializeDataListView();
            LoadFileData();
            BindData();
        }

        // 初始化图标列表
        private void InitializeImageList()
        {
            _fileImageList = new ImageList
            {
                ImageSize = new Size(16, 16), // 标准小图标尺寸
                ColorDepth = ColorDepth.Depth32Bit // 高质量图标
            };
            _iconCache = new IconCache(_fileImageList);
        }

        // 初始化DataListView
        private void InitializeDataListView()
        {
            _dataListView = new DataListView
            {
                Dock = DockStyle.Fill,
                View = View.Details,
                GridLines = true,
                FullRowSelect = true,
                SmallImageList = _fileImageList, // 关联图标列表
                UseAlternatingBackColors = true,
                ShowGroups = false
            };

            // 添加列（包含图标列）
            _dataListView.Columns.AddRange(new OLVColumn[]
            {
                // 图标列（通过ImageGetter获取图标）
                new OLVColumn("文件路径", "文件路径1")
                {
                    Width=300,
                    ImageGetter = (row)=>{
                        Console.WriteLine(row.ToString());
                        return "xx";
                    }  // 关键：设置图标获取器
                },
                new OLVColumn("文件名", "文件名2") { Width = 100 },
                new OLVColumn("类型", "类型3") { Width = 150 },
                new OLVColumn("大小", "大小4")
                {
                    Width = 200,
                    TextAlign = HorizontalAlignment.Center
                },
                new OLVColumn("修改日期", "修改日期5") { Width = 180 }
            });

            Controls.Add(_dataListView);
        }

        // 获取文件图标索引（供ImageGetter使用）
        private int GetFileIconIndex(object rowObject)
        {
            if (rowObject is DataRowView row)
            {
                string filePath = row["FilePath"].ToString();
                return _iconCache.GetIconIndex(filePath);
            }
            return -1; // 无图标
        }

        // 加载文件数据
        private void LoadFileData()
        {
            _fileData = new DataTable("FileData");
            _fileData.Columns.AddRange(new DataColumn[]
            {
                new DataColumn("文件路径1", typeof(string)), // 存储完整路径用于获取图标
                new DataColumn("文件名2", typeof(string)),
                new DataColumn("类型3", typeof(string)),
                new DataColumn("大小4", typeof(string)),
                new DataColumn("修改日期5", typeof(DateTime))
            });

            // 获取桌面目录文件作为示例
            string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            if (Directory.Exists(desktopPath))
            {
                // 添加目录
                foreach (string dirPath in Directory.GetDirectories(desktopPath))
                {
                    var dirInfo = new DirectoryInfo(dirPath);
                    _fileData.Rows.Add(
                        dirPath,
                        dirInfo.Name,
                        "文件夹",
                        "",
                        dirInfo.LastWriteTime
                    );
                }

                // 添加文件
                foreach (string filePath in Directory.GetFiles(desktopPath))
                {
                    try
                    {
                        var fileInfo = new FileInfo(filePath);
                        _fileData.Rows.Add(
                            filePath,
                            fileInfo.Name,
                            GetFileTypeDescription(filePath),
                            FormatFileSize(fileInfo.Length),
                            fileInfo.LastWriteTime
                        );
                    }
                    catch
                    {
                        // 跳过无权限访问的文件
                    }
                }
            }
        }

        // 获取文件类型描述
        private string GetFileTypeDescription(string filePath)
        {
            string ext = Path.GetExtension(filePath).ToLower();
            var typeMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
            {
                { ".txt", "文本文件" },
                { ".docx", "Word文档" },
                { ".xlsx", "Excel表格" },
                { ".pdf", "PDF文档" },
                { ".jpg", "JPEG图像" },
                { ".png", "PNG图像" },
                { ".exe", "应用程序" },
                { ".dll", "动态链接库" }
            };

            return typeMap.TryGetValue(ext, out string desc) ? desc : $"{ext}文件";
        }

        // 格式化文件大小
        private string FormatFileSize(long bytes)
        {
            if (bytes < 1024)
                return $"{bytes} B";
            if (bytes < 1024 * 1024)
                return $"{bytes / 1024.0:F1} KB";
            return $"{bytes / (1024.0 * 1024):F1} MB";
        }

        // 绑定数据
        private void BindData()
        {
            _dataListView.DataSource = _fileData;
        }
    }
}
